﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Factory;
using BLL;
using System.Data;

namespace MyWorkspace
{
    public partial class UpdateAuthority : System.Web.UI.Page
    { 
        private static String authorityId;
        protected void Page_Load(object sender, EventArgs e)
        { 
           
            if (!IsPostBack)
            {
                //第一步，把所有的LevelName放置到UpdateLevel中
                IAuthorityRepository authoritymanage = AuthorityManageFactory.InitializeAuthorityRepository();
                this.UpdateLevel.DataSource = authoritymanage.GetAllAuthorityLevelName();
                this.UpdateLevel.DataTextField = "LevelName";
                this.UpdateLevel.DataValueField = "LevelId";
                this.UpdateLevel.DataBind();

                //第二步，把通过传参authorityId得到的AuthorityName传到TextBox
                authorityId = Request.QueryString["id"].ToString();
                Authority authoritydetails = authoritymanage.GetAuthorityDetails(int.Parse(authorityId));//获取该Id的详情
                this.UpdateName.Text = authoritydetails.AuthorityName;

                //第三步，根据urlid得到的LevelId，然后循环获取LevelName
                for(int i=0;i <this.UpdateLevel.Items.Count;i++)
                {
                    if (this.UpdateLevel.Items[i].Value == authoritydetails.Level.LevelId.ToString())
                    {
                        this.UpdateLevel.Items[i].Selected=true;
                    }
                } 
            }
        }

        protected void SaveButton_Click(object sender, EventArgs e)
        {
            if (UpdateName.Text.Length == 0)
            {
                Response.Write("<script>alert('AuthorityName is null!')</script>");
            }
            else
            {
                string newUpdateName = UpdateName.Text;//得到文本框输入的字符串
                string newLevelName = this.UpdateLevel.SelectedItem.Text;//得到LeveName

                IAuthorityRepository authorityUpdate = AuthorityManageFactory.InitializeAuthorityRepository();
                Authority authority = new Authority();
                authority.AuthorityName = newUpdateName;
                authority.Level.LevelId = int.Parse(UpdateLevel.SelectedValue);
                authority.AuthorityId = int.Parse(authorityId);
                authorityUpdate.UpdateAuthority(authority);
                authority.Level.LevelName = UpdateLevel.SelectedItem.Text;
                Response.Redirect("AuthorityList.aspx");//页面跳转
            }
           
        }
    }
}